package com.shangcheng.background.controller;

import com.github.pagehelper.PageInfo;
import com.shangcheng.users.feign.UserFeign;
import com.shangcheng.users.pojo.User;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;


@Controller
@RequestMapping(value = "/bg")
public class BgUserController {
    @Autowired
    private UserFeign userFeign;

    @GetMapping(value = "/user/bguser")
    public String user(ModelMap model) {
        Result<PageInfo> result = userFeign.findPage(1, 20);
        model.addAttribute("users", result.getData().getList());
        return "bguser";
    }

    @PostMapping(value = "/user/add")
    public String add(@RequestParam String username,
                      @RequestParam String password,
                      @RequestParam String phone,
                      @RequestParam String email,
                      @RequestParam String qq,
                      ModelMap model) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setPhone(phone);
        user.setEmail(email);
        user.setQq(qq);
        Date date = new Date();
        user.setCreated(date);
        user.setUpdated(date);
        Result result = userFeign.add(user);
        model.addAttribute("save", result.getMessage());
        Result<PageInfo> resul = userFeign.findPage(1, 20);
        model.addAttribute("users", resul.getData().getList());
        return "bguser";
    }

    @GetMapping("/user/findBy")
    public String findById(@RequestParam String username, ModelMap model) {
        Result<User> userResult = userFeign.findByName(username);
        model.addAttribute("save", userResult.getMessage());
        model.addAttribute("user", userResult.getData());
        return "bguser-su";
    }

    @GetMapping("/user/delete")
    public String delete(@RequestParam String username, ModelMap model) {
        Result result = userFeign.delete(username);
        model.addAttribute("save", result.getMessage());
        Result<PageInfo> resul = userFeign.findPage(1, 20);
        model.addAttribute("users", resul.getData().getList());
        return "bguser";
    }
}
